/**
 * Created by yhg97p on 2016/9/27.
 * 全局控制，进行权限操作等
 */
define(['app', 'services/services'], function (app) {
    app.register.controller('appCtrl', function ($scope, $http, $state, $cookieStore, $rootScope, $prompt, $timeout, $window) {
        $rootScope.permissions = true;
        $rootScope.body_style = {
            'overflow': 'auto'
        };
        $scope.$state = $state;
        //用户退出
        $rootScope.logout = function (hash) {
            $http({
                url: app._baseUrl + '/Pub/Public/logout',
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            }).success(function (responed) {
                if (responed.success) {
                    $cookieStore.remove('userInfo');    //移除用户cookie
                    $state.go('access.login');     //跳转登录页
                } else {
                    //$scope.authError = responed.message;
                    //弹出提示？
                }

            });
        };
        $scope.app = {};
        //启动时验证是否登录
        $rootScope.checkLogin = function () {
            if ($cookieStore.get('userInfo')) {
                $scope.app.user = $rootScope.user = JSON.parse($cookieStore.get('userInfo'));
                $rootScope.permissions = true;
                return false;
                // $scope.app.user.photo.length==0||$scope.app.user.photo=='http://localhost/qiyepeixun'?$rootScope.hasimg = true:$rootScope.hasimg = false;//定义在全局判断用户是否有头像
            } else {  //清除rootscope用户信息
                // if ($state.includes('app.proIndex') || $state.includes('app.signUp')) {//v1.0.6版本去掉产品模块
                //     return
                // } else {
                //     $state.go('access.login');
                //     $scope.app.user = $rootScope.user = '';
                // }

                   //v1.0.6版本加的两行代码
                   //  $state.go('access.login');
                   //  $scope.app.user = $rootScope.user = '';

                if ($state.includes('app.informationEntry') || $state.includes('app.reviewtheTopic')) {//v1.0.8版本加

                    return false;
                } else {
                    $state.go('access.login');
                    $scope.app.user = $rootScope.user = '';
                }
            }
        };
        $rootScope.checkLogin();
        //监视路由页面切换，判断用户是否登录
        $rootScope.$on('$stateChangeStart', function (event, toState, toParams, formState, forParams) {
            angular.element($window).unbind('scroll');
            if ($cookieStore.get('userInfo')) {
                $scope.top_right = false;
            }
            if (formState.name == 'access.login' || formState.name == 'access.register' || formState.name == 'app.informationEntry'|| formState.name == 'app.reviewtheTopic') return;   //登录页面则不需要监视
            // 未登录
            if (!$rootScope.user) {
                $state.go('access.login'); //跳转到登录界面
                event.preventDefault();// 取消默认跳转行为
            }
        });
        //监视登录登录状态
        $rootScope.$on('userIntercepted', function (event, errorType) {
            switch (errorType) {
                case '-103':
                    // $prompt.timeout($scope, {code: '', message: '您尚未登录，无法进行任何操作，请登录后重试！'});
                    $cookieStore.remove('userInfo');
                    if ($state.includes('app.informationEntry') || $state.includes('app.reviewtheTopic')) {//v1.0.6版本去掉的

                    } else {
                        $timeout(function () {
                            $state.go('access.login');
                        }, 300);
                    }
                    //     $timeout(function () {//v1.0.6版本加
                    //         $state.go('access.login');
                    //     }, 300);
                    break;
                case '-101':
                    $prompt.timeout($scope, { code: '', message: '服务器错误，请稍后重试！' });
                    break;
            }
            return false;
        });

        //判断页面是否需要登录
        if($rootScope.user){
            $http({
                url: app._baseUrl + '/QyManage/Setting/detail',
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }).success(function (res) {
                if (res.success == true) {
                    $scope.Compinfo = res.data;
                } else {
                    // console.log(res)
                }

            });
            $http({//个人信息、头像
                url: app._baseUrl + '/Pub/Account/detail',
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }).success(function (res) {
                if (res.success == true) {
                    $scope.Information = res.data;
                    $rootScope.userName = $scope.Information.user_name;
                    if ($scope.Information.photo == '') {
                        $rootScope.hasimg = true;
                    }
                }

            });
        }


        $scope.includeMenu = function (e) {
            if (e == 'product') {
                if ($state.includes('app.proIndex') || $state.includes('app.signUp')) {
                    return true;
                } else {
                    return false;
                }
            } else if (e == 'myCenter') {
                if ($state.includes('app.myCourse') || $state.includes('app.myTask') || $state.includes('app.myMajor') || ($state.includes('app.myCoursenew')) || ($state.includes('app.ablityAssessRecord'))) {
                    return true;
                }else {
                    return false;
                }
            } if (e == 'company') {
                if ($state.includes('app.compProfession') || $state.includes('app.compTask') || $state.includes('app.compLive') || ($state.includes('app.compCourse'))) {
                    return true;
                } else {
                    return false;
                }
            } if (e == 'circularize') {
                if ($state.includes('app.circularize')) {
                    return true
                } else {
                    return false
                }
            }if(e == 'company_tool'){
                if ($state.includes('app.abilityAssess') || $state.includes('app.compReport') || $state.includes('app.compMember') ||
                    $state.includes('app.compSet') || $state.includes('app.compActivity')) {
                    return true;
                }else {
                    return false;
                }
            }if(e == 'capacityAssessment'){
                if ($state.includes('app.informationEntry')||$state.includes('app.reviewtheTopic')){
                    return false;
                }else {
                    return true;
                }
            }
            $scope.app.user.data.photo.length == 0 || $scope.app.user.data.photo == 'http://localhost/qiyepeixun' ? $rootScope.hasimg = true : $rootScope.hasimg = false;//定义在全局判断用户是否有头像
            //console.log($scope.app.user.photo)

        }

        $scope.addclass = 0;
        $scope.add_class = 0;
        //跳转
        $scope.statego = function (hash) {
            if ($cookieStore.get('nl_tc') == 1) {
                $rootScope.show_nl_tc = true;
                $cookieStore.put('nl_tc', 0);
                $rootScope.hash = 'app.proIndex';
                return false;
            }
            $("html,body").animate({ scrollTop: 0 }, 0)
            $(".header_wrap_product1").removeClass("header_wrap_style");
            $cookieStore.put('refurbish', 1);
            if (hash == "app.proIndex") {

            }
            if ($rootScope.permissions) {
                $rootScope.states = 0;
                $state.go(hash);

            } else {
                $state.go('access.login');
            }

        };
        $scope.goPro = function (hash) {
            $state.go(hash);
        }
        $scope.stategoParam = function (hash, param) {
            $state.go(hash, param);
        };
        $rootScope.goComp = function (hash) {
            // console.log($cookieStore.get('nl_tc'))
            if ($cookieStore.get('nl_tc') == 1) {
                $rootScope.show_nl_tc = true;
                if ($rootScope.show_nl_tc == true) {
                    $cookieStore.put('nl_tc', 0);
                    $rootScope.hash = 'app.compProfession';
                    return false;
                }
            }
            $(".header_wrap_product1").removeClass("header_wrap_style");
            if (hash == "app.compProfession") {
                $cookieStore.put('refurbish', 1)
                $("html,body").animate({ scrollTop: 0 }, 0)
            }
            if ($cookieStore.get('userInfo')) {
                var url = $state.href('app.compProfession');
                window.location.href = url;
            } else {
                $state.go('access.login');
            }
        }
        $scope.stategoCheck = function (hash) {
            if ($cookieStore.get('nl_tc') == 1) {
                $rootScope.show_nl_tc = true;
                $cookieStore.put('nl_tc', 0);
                $rootScope.hash = 'app.myCourse';
                return false;
            }
            $(".header_wrap_product1").removeClass("header_wrap_style");
            $cookieStore.put('refurbish', 1)
            if (hash == "app.myMajor") {
            }
            $("html,body").animate({ scrollTop: 0 }, 0)
            if ($cookieStore.get('userInfo') && (hash == "app.proIndex" || hash == "app.signUp||app.myMajor")) {
                $state.go(hash);
            } else if ($cookieStore.get('userInfo') || hash == "app.proIndex" || hash == "app.signUp||app.myMajor") {
                $state.go(hash);
            } else {
                $state.go('access.login');
            }
        }
        //判断是否登录
        if (!$cookieStore.get('userInfo')) {
            $scope.top_right = true;
        }
        if($cookieStore.get('userInfo')){
            // 未读数量判断
            $rootScope.messageCount = 0;
            $http.get(app._baseUrl + '/Message/Message/noReadCount').success(
                function (result) {
                    // return $scope.messageCount += 1;
                    if(result.data) {
                        return $rootScope.messageCount = result.data.no_read_count;
                    }
                }
            )
             setInterval(function () {
                 $http.get(app._baseUrl + '/Message/Message/noReadCount').success(
                     function (result) {
                         if(result.data) {
                             // return $scope.messageCount += 1;
                             return $rootScope.messageCount = result.data.no_read_count;
                         }
                     }
                 )
            }, 60000);
        }
        //头像hover状态
        $scope.headerHover = {
            header_hover:function(){
                $('.pull_down').stop().fadeIn();
            },
            header_hover_l:function(){
                $('.pull_down').stop().fadeOut();
            }
        };
    })

});
